package aduros.display {

import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.filters.ColorMatrixFilter;

public class ImageButton extends Sprite
{
    public function ImageButton (
        iconDefault :Bitmap, toolTip :String = null, iconToggled :Bitmap = null)
    {
        _iconDefault = iconDefault;
        _iconToggled = iconToggled;

        _skin.addChild(_iconDefault);
        addChild(_skin);

        addEventListener(MouseEvent.ROLL_OVER, function (event :MouseEvent) :void {
            _hovering = true;
            update();
        });
        addEventListener(MouseEvent.ROLL_OUT, function (... _) :void {
            _hovering = false;
            update();
            _skin.y = 0;
        });

        if (toolTip != null) {
            ToolTipManager.instance.attach(this, toolTip);
        }

        addEventListener(MouseEvent.MOUSE_DOWN, function (... _) :void {
            _skin.y = 2;
        });
        addEventListener(MouseEvent.MOUSE_UP, function (... _) :void {
            _skin.y = 0;
        });

        buttonMode = true;
        mouseChildren = false;
    }

    public function set toggled (on :Boolean) :void
    {
        _skin.removeChild(_toggled ? _iconToggled : _iconDefault);
        _toggled = on;
        _skin.addChild(_toggled ? _iconToggled : _iconDefault);
    }

    public function get toggled () :Boolean
    {
        return _toggled;
    }

    public override function set mouseEnabled (enabled :Boolean) :void
    {
        super.mouseEnabled = enabled;

        update();
    }

    protected function update () :void
    {
        if (mouseEnabled) {
            if (_hovering) {
                _skin.filters = BRIGHTEN;
            } else {
                _skin.filters = null;
            }
        } else {
            _skin.filters = DESATURATE;
            _skin.y = 0;
        }
    }

    protected static const DESATURATE :Array = [ new ColorMatrixFilter([
        1/3, 1/3, 1/3, 0, 0,
        1/3, 1/3, 1/3, 0, 0,
        1/3, 1/3, 1/3, 0, 0,
        0, 0, 0, 1, 0
    ]) ];

    protected static const BRIGHTEN :Array = [ new ColorMatrixFilter([
        1.25, 0, 0, 0, 0,
        0, 1.25, 0, 0, 0,
        0, 0, 1.25, 0, 0,
        0, 0, 0, 1, 0
    ]) ];

    protected var _skin :Sprite = new Sprite();

    protected var _iconDefault :Bitmap;
    protected var _iconToggled :Bitmap;

    protected var _hovering :Boolean;
    protected var _toggled :Boolean;
}

}
